package com.small.admin.controller;

import com.small.admin.dto.AdminInfo;
import com.small.admin.entity.Admin;
import com.small.admin.entity.Menu;
import com.small.admin.service.AdminService;
import com.small.admin.service.MenuService;
import com.small.admin.service.RoleAdminService;
import com.small.admin.service.RoleMenuService;
import com.small.common.msg.Msg;
import com.small.common.msg.MsgData;
import com.small.common.util.jwt.JwtTokenUtil;
import com.small.common.util.jwt.info.impl.JwtInfoImpl;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017/11/25 16:54
 * 描述:
 */
public class BaseLoginController {

    @Resource
    private RoleMenuService roleMenuService;

    @Resource
    private MenuService menuService;

    @Resource
    private RoleAdminService roleAdminService;

    @Resource
    private JwtTokenUtil adminJwtTokenUtil;

    @Resource
    public AdminService adminService;

    /**
     * 登录成功处理返回结果
     *
     * @param admin 用户信息
     */
    public Msg storageSession(Admin admin) throws Exception {
        //登录成功清空登录错误次数记录
        Admin updateAdmin = new Admin();
        updateAdmin.setId(admin.getId());
        updateAdmin.setLoginError(0);
        updateAdmin.setState(1);
        adminService.updateSelectiveById(admin);
        int isSystem = admin.getIsSystem();
        //得到启用菜单
        List<Menu> menusList = menuService.selectListByState(1);
        AdminInfo adminInfo = new AdminInfo();
        JwtInfoImpl ijwtInfo = new JwtInfoImpl();
        ijwtInfo.setName(admin.getName());
        ijwtInfo.setAccount(admin.getAccount());
        ijwtInfo.setId(admin.getId());
        ijwtInfo.setIsSystem(isSystem);
        //普通管理员
        if (isSystem == 0) {
            //读取用户拥有的菜单权限
            List<Long> menusRight = roleMenuService.selectByAdminMenu(admin.getId());
            Set<String> right = new HashSet<>();
            for (Iterator<Menu> it = menusList.iterator(); it.hasNext(); ) {
                Menu menu = it.next();
                if (menusRight.contains(menu.getId())) {
                    right.add(menu.getUrl());
                } else {
                    it.remove();
                }
            }
            //可以访问的URL集合
            adminInfo.setRight(right);
            //将用户拥有的角色写入token
            List<Long> roles = roleAdminService.selectByAdminId(admin.getId());
            if (roles != null) {
                ijwtInfo.setRoles(StringUtils.join(roles, ","));
            }
        }
        adminInfo.setIsSystem(isSystem);
        adminInfo.setName(admin.getName());
        adminInfo.setMenusList(menusList);
        //将token返回给客户
        adminInfo.setToken(adminJwtTokenUtil.generateToken(ijwtInfo));
        return new MsgData<>(adminInfo);
    }

}
